#include "userdao.h"
#include <QSqlQuery>
#include <QSqlRecord>
#include <QVariant>
#include <QDebug>
#include <QSqlError> // 新增：添加QSqlError头文件R

UserDao *UserDao::instance = nullptr;

bool UserDao::insertUser(UserEntity ue, bool &ok)
{
    QSqlQuery query;
    query.prepare("select * from user where name = ?");
    query.bindValue(0,ue.name);
    bool execok = query.exec();
    if(query.next())
    {
        ok = false;
        return execok;
    }

    query.prepare("insert into user(name,password) values(?,?)");
    query.bindValue(0,ue.name);
    query.bindValue(1,ue.password);
    execok = query.exec();
    ok = true;
    return execok;
}

bool UserDao::selectUser(UserEntity ue, bool &ok)
{
    QSqlQuery query;
    query.prepare("select * from user where name = ? and password = ?");
    query.bindValue(0,ue.name);
    query.bindValue(1,ue.password);
    bool execok = query.exec();

    ok = query.next();
    return execok;
}

UserDao::UserDao(const UserDao &other)
{

}

UserDao::UserDao()
{
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setHostName("playerdb");
    db.setDatabaseName("playerdb.db");
    db.open();

    QSqlQuery query;
    bool ok = query.exec("create table if not exists user("
                         "id integer primary key autoincrement,"
                         "name char(20),"
                         "password char(20)"
                         ")");
    qDebug() << "创建user表 " << ok;
}

UserDao::~UserDao()
{
    db.close();
}

UserDao *UserDao::getInstance()
{
    if(instance == nullptr)
    {
        instance = new UserDao;
    }
    return instance;
}

void UserDao::releaseInstance()
{
    if(instance != nullptr)
    {
        delete instance;
        instance = nullptr;
    }
}

int UserDao::verifyUser(const QString &username, const QString &password)
{
    if (!db.isOpen()) {
       qDebug() << "数据库未打开，无法验证用户";
       return -1;
    }

    QSqlQuery query(db);
    // 查询user表中是否存在匹配的用户名和密码
    // 注意：这里假设你的用户表名为"user"，字段为"username"、"password"、"id"
    query.prepare("SELECT id FROM user WHERE name = :username AND password = :password");
    query.bindValue(":username", username);
    query.bindValue(":password", password);

    if (!query.exec()) {
        qDebug() << "用户验证查询失败：" << query.lastError().text();
        return -1;
    }

    // 如果查询到结果，返回用户ID；否则返回-1
    if (query.next()) {
        return query.value(0).toInt(); // 返回id字段的值
    } else {
        return -1; // 用户名或密码错误
    }
}

